import axios from 'axios';

const API_URL = import.meta.env.VITE_API_URL || `http://${window.location.hostname}:3001/api`;

export interface LoginCredentials {
  email: string;
  password: string;
}

export interface RegisterData {
  username: string;
  email: string;
  password: string;
  adminCode?: string;
  name?: string;
}

export interface User {
  id: string;
  username: string;
  email: string;
  role: 'admin' | 'user';
}

export interface AuthResponse {
  token: string;
  user: User;
}

class AuthService {
  private token: string | null = null;
  private user: User | null = null;

  constructor() {
    // 从 localStorage 恢复认证状态
    this.token = localStorage.getItem('token');
    const userStr = localStorage.getItem('user');
    if (userStr) {
      try {
        this.user = JSON.parse(userStr);
      } catch (e) {
        console.error('Failed to parse user data:', e);
        this.clearAuth();
      }
    }

    // 设置 axios 拦截器
    axios.interceptors.request.use(
      (config) => {
        if (this.token) {
          config.headers.Authorization = `Bearer ${this.token}`;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // 添加响应拦截器处理401错误
    axios.interceptors.response.use(
      (response) => response,
      (error) => {
        if (error.response?.status === 401) {
          this.clearAuth();
          window.location.href = '/login';
        }
        return Promise.reject(error);
      }
    );
  }

  private setAuth(token: string, user: User) {
    this.token = token;
    this.user = user;
    localStorage.setItem('token', token);
    localStorage.setItem('user', JSON.stringify(user));
  }

  private clearAuth() {
    this.token = null;
    this.user = null;
    localStorage.removeItem('token');
    localStorage.removeItem('user');
  }

  public isAuthenticated(): boolean {
    return !!this.token && !!this.user;
  }

  public isAdmin(): boolean {
    return this.user?.role === 'admin';
  }

  public getToken(): string | null {
    return this.token;
  }

  public getUser(): User | null {
    return this.user;
  }

  public getCurrentUser(): User | null {
    return this.user;
  }

  public async login(credentials: LoginCredentials): Promise<AuthResponse> {
    try {
      const response = await axios.post<AuthResponse>(`${API_URL}/auth/login`, credentials);
      const { token, user } = response.data;
      this.setAuth(token, user);
      return response.data;
    } catch (error: any) {
      this.clearAuth();
      if (error.response?.status === 401) {
        throw new Error('邮箱或密码错误');
      } else if (error.response?.status === 500) {
        throw new Error('服务器错误，请稍后重试');
      } else {
        throw new Error(error.response?.data?.message || '登录失败，请稍后重试');
      }
    }
  }

  public async register(data: RegisterData): Promise<AuthResponse> {
    try {
      const response = await axios.post<AuthResponse>(`${API_URL}/auth/register`, data);
      const { token, user } = response.data;
      this.setAuth(token, user);
      return response.data;
    } catch (error: any) {
      this.clearAuth();
      if (error.response?.status === 400) {
        throw new Error(error.response.data.message || '注册信息无效');
      } else if (error.response?.status === 500) {
        throw new Error('服务器错误，请稍后重试');
      } else {
        throw new Error(error.response?.data?.message || '注册失败，请稍后重试');
      }
    }
  }

  public logout() {
    this.clearAuth();
    window.location.href = '/login';
  }

  public async verifyResetToken(token: string): Promise<boolean> {
    try {
      await axios.get(`${API_URL}/auth/verify-reset-token/${token}`);
      return true;
    } catch (error: any) {
      return false;
    }
  }

  public async resetPassword(email: string): Promise<void> {
    try {
      await axios.post(`${API_URL}/auth/reset-password`, { email });
    } catch (error: any) {
      throw error;
    }
  }

  public async updatePassword(token: string, password: string): Promise<void> {
    try {
      await axios.post(`${API_URL}/auth/update-password`, { token, password });
    } catch (error: any) {
      throw error;
    }
  }
}

export default new AuthService(); 